<!-- 子组件 YdDialog.vue -->
<template>
  <div
    ref="containerRef"
    v-if="show"
    class="dialog-container"
    tabindex="0"
    v-click-outside="close"
    :style="dialogStyle"
  >
    <slot></slot>
  </div>
</template>

<script setup>
import { ref, nextTick, watch, onMounted, onUnmounted } from 'vue'

const props = defineProps({
  show: Boolean,
  x: {
    type: Number,
    default: 0
  },
  y: {
    type: Number,
    default: 0
  }
})

const emit = defineEmits(['update:show'])
const containerRef = ref(null)

// 创建唯一ID来标识每个对话框实例
const dialogId = Math.random().toString(36).substr(2, 9)

// 全局对话框管理
if (!window.__dialogManager) {
  window.__dialogManager = {
    currentDialogId: null,
    dialogs: new Map()
  }
}

// 计算后的位置样式
const dialogStyle = ref({
  position: 'fixed',
  left: '0px',
  top: '0px'
})

// 关闭函数
const close = () => {
  emit('update:show', false)
}

// 边界处理和位置计算 - 智能定位在鼠标周围
const calculatePosition = async () => {
  // console.log('calculatePosition 被调用了')
  // console.log('containerRef.value:', containerRef.value)

  if (!containerRef.value) {
    // console.log('containerRef.value 为空，直接返回')
    return
  }
  // console.log(3)
  // 先设置一个临时位置来获取真实尺寸
  dialogStyle.value = {
    position: 'fixed',
    left: `${props.x}px`,
    top: `${props.y}px`,
    visibility: 'hidden'
  }

  await nextTick()

  const dialog = containerRef.value
  if (!dialog) return

  const rect = dialog.getBoundingClientRect()
  const viewportWidth = window.innerWidth
  const viewportHeight = window.innerHeight
  const margin = 10
  const xOffset = 20 // 距离鼠标的偏移量
  const yOffset = 10 // 距离鼠标的偏移量
  const offset = 8

  let finalX = props.x + xOffset
  let finalY = props.y - yOffset

  // console.log('最终:' , finalX , finalY)


  // 检查右边界
  if (finalX + rect.width > viewportWidth - margin) {
    finalX = props.x - rect.width - xOffset // 显示在左侧
  }

  // 检查下边界
  if (finalY + rect.height > viewportHeight - margin) {
    finalY = props.y - rect.height - yOffset // 显示在上方
  }

  // 确保不超出左边界
  if (finalX < margin) {
    finalX = margin
  }

  // 确保不超出上边界
  if (finalY < margin) {
    finalY = margin
  }

  // 最终设置位置并显示
  dialogStyle.value = {
    position: 'fixed',
    left: `${finalX}px`,
    top: `${finalY}px`,
    visibility: 'visible'
  }
}

// 注册对话框
onMounted(() => {
  window.__dialogManager.dialogs.set(dialogId, { close })
})

// 清理对话框
onUnmounted(() => {
  window.__dialogManager.dialogs.delete(dialogId)
  if (window.__dialogManager.currentDialogId === dialogId) {
    window.__dialogManager.currentDialogId = null
  }
})

// 监听显示状态变化
watch(() => props.show, async (newVal) => {
  // console.log(1)
  if (newVal) {
    // console.log(2)
    // 关闭其他对话框
    const currentId = window.__dialogManager.currentDialogId
    if (currentId && currentId !== dialogId) {
      const currentDialog = window.__dialogManager.dialogs.get(currentId)
      if (currentDialog) {
        currentDialog.close()
      }
    }

    // 设置当前对话框
    window.__dialogManager.currentDialogId = dialogId

    // 等待 DOM 渲染完成后再计算位置
    await nextTick()
    await calculatePosition()
  } else {
    if (window.__dialogManager.currentDialogId === dialogId) {
      window.__dialogManager.currentDialogId = null
    }
  }
})

// 监听位置变化
watch([() => props.x, () => props.y], async () => {
  if (props.show) {
    await calculatePosition()
  }
})
</script>

<style scoped lang="less">
.dialog-container {
  border-radius: 10px;
  background-color: white;
  box-shadow: 0 0 10px #c1c0c0;
  outline: none;
  z-index: 1000;
}
</style>
